// pages/confirm/confirm.js
var util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartListData: [],
    buyCount: 0, //购物车总数量
    allPrice: 0, //购物车总价
    allDiscount: 0, //购物车总折扣
    orderRemark: '',
    deliveryCost: 0, //订单配送费
    extraDeliveryCost: 0, //订单附加服务费
    //---------------订单支付成功轮询参数
    successOrderInfo: null,
    timer: null,
    //---------------以下参数为订生成动画用变量
    showWaiting: false,
    progress_txt: '订单生成中...',
    count: 0, // 设置 计数器 初始为0
    countTimer: null, // 设置 定时器 初始为null
    payType: ['微信支付', '积分支付'],
    //---------------以下参数为临时变量，不在视图层交互
    payTypeIndex: 0, //用来临时存储支付类型，不在视图层显示
    orderId: null, //用来临时存储订单编号，不在视图层显示
    prepayId: '', //用来临时存储此次交易的preyid，不在视图层交互
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},
  //--------------------------------------------当用户点击【配送地址】栏时
  selectAddressClick: function () {
    // wx.navigateTo({
    //   url: '../../pages/addressList/addressList',
    // })
    wx.showModal({
      title: '配送地址更改',
      content: '请移至首页，将为您保留购物车中的产品',
      cancelText: '取消',
      confirmText: '立即更改',
      complete: function (res) {
        if (res.confirm) {
          getApp().globalData.back_to_change_orderType = true
          wx.navigateBack({
            delta: 2
          })
        }
      }
    })
  },
  //--------------------------------------------当用户点击【订单类型】栏时
  orderTypeClick: function () {
    wx.showModal({
      title: '就餐方式更改',
      content: '请移至首页，将为您保留购物车中的产品',
      cancelText: '取消',
      confirmText: '立即更改',
      complete: function (res) {
        if (res.confirm) {
          getApp().globalData.back_to_change_orderType = true
          wx.navigateBack({
            delta: 2
          })
        }
      }
    })
  },
  //--------------------------------------------当picker的时间改变时
  bindTimeChange: function (e) {
    console.log(e.detail.value)
    this.setData({
      'order.orderTime': e.detail.value
    })
  },
  //--------------------------------------------同步数据
  dataTransport: function () {
    //获取内存中的购物车数据
    var cartList = wx.getStorageSync('cartList')
    if (cartList == "") {
      this.setData({
        cartListData: [], //购物车列表数据
        order: getApp().globalData.order
      })
    } else {
      //console.log(cartList)
      this.setData({
        cartListData: cartList,
        order: getApp().globalData.order
      })
    }
    //根据存储的购物车信息，刷新购买总数量和购买总价格
    this.freshBuyCountAndallPrice();
  },
  //--------------------------------------------刷新购物车 总数量及价格
  freshBuyCountAndallPrice: function () {

    var cartListData = this.data.cartListData;
    var buyCount = 0;
    var allPrice = 0;
    var allDiscount = 0;
    for (var i = 0; i < cartListData.length; i++) {
      buyCount += cartListData[i].count
      allPrice += cartListData[i].price * 10
      allDiscount += cartListData[i].discount * 10
    }
    console.log(allPrice / 10)
    this.setData({
      buyCount: buyCount,
      allPrice: allPrice / 10,
      allDiscount: allDiscount / 10
    })
  },
  //--------------------------------------------当填写完备注：赋值到data中的orderRemark
  remarkInputComplete: function (e) {
    this.setData({
      orderRemark: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //1.其他页面的数据同步
    this.dataTransport();
    //2.从服务器同步店铺设置
    util.queryShopSettings().then(res => {

      let settings = res.data

      //2.1 将店铺设置同步至全部变量
      getApp().globalData.settings = settings

      //2.2 计算运费和附加服务费
      let deliveryCost = getApp().globalData.deliveryCost
      let extraDeliveryCost = getApp().globalData.extraDeliveryCost

      this.setData({
        deliveryCost: deliveryCost,
        extraDeliveryCost: extraDeliveryCost,
        allPrice: this.data.allPrice + deliveryCost + extraDeliveryCost,
      })
    }).catch(res => {
      //查询不到店铺设置，说明网络错误
      wx.navigateBack({
        delta: 1
      })
      wx.showModal({
        title: '请检查网络状态',
        content: '请检查您的网络并稍后再试',
        showCancel: false
      })
    })


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  //----------------------------------------------- 去支付按钮
  goToPay: function () {
    //****************去支付前校验内容****************
    //1.当为【外卖配送】时，所选地址是否在派送支持范围内
    if (this.data.order.typeId == 3) {
      let distance = Number(this.data.order.addressInfo.distance) //当前所选地址距离
      let sendDistance = getApp().globalData.settings.sendDistance //获取最新的店铺设置中的派送距离
      if (Number(distance) > Number(sendDistance)) {
        wx.showModal({
          title: '超出派送范围(' + (sendDistance / 1000).toFixed(1) + '公里内)',
          content: '请点击地址栏重新选择',
          showCancel: false
        })
        return; //退出支付程序
      }
    }
    //***********************************************
    var that = this;
    //弹出列表，供用户选择支付方式
    let payType = this.data.payType;
    wx.showActionSheet({
      itemList: payType,
      itemColor: '#3CC51F',
      success: function (res) {
        console.log(res.tapIndex)
        //记录至payTypeIndex
        that.data.payTypeIndex = res.tapIndex
        if (res.tapIndex == 0) //用户选择了微信支付
        {
          that.cloudWeiXinPay();
        } else if (res.tapIndex == 1) //用户选择了积分支付
        {
          that.payByVipPoints();
        }
      },
      fail: function (res) {
        //用户进行了取消操作，啥也不需要干
        console.log(res.errMsg)
      }
    })
  },
  //---------------------------request：微信支付，为wx.requestPayment获取参数
  getWexinPayParameters: function () {
    let that = this;
    wx.showLoading({
      title: '正在发起支付'
    });
    //************   获取需要传入的参函数   ************
    //(1)openid ：调用云函数自带openid
    //(2)订单总额:单位为分
    let totalFee = this.data.allPrice * 10 * 10 //订单总金额
    totalFee = Math.round(totalFee)
    console.log('totalFee:' + totalFee)
    //(3)订单号：生成唯一订单号，先生成，如果支付成功，则写入数据库成为正式订单号，否则废弃
    let outTradeNo = that.genOrderId();
    console.log("订单号：", outTradeNo)
    //----------------------------------------------------------------------------------

    //************   将订单信息上传至 订单信息中转站   ************
    that.uploadTempOrderInfo().then(res => {
      let result = res.result.result //订单信息是否上传成功
      if (result == 'fail')
      // a.临时信息上传失败
      {
        wx.hideLoading()
        wx.showModal({
          title: '发起支付失败',
          content: '请检查您的网络状态后再试',
          showCancel: false
        })
      } else {
        // b.临时信息上传成功

        //************   调用云函数:weixinPay   ************
        wx.cloud.callFunction({
            name: 'weixinPay',
            data: {
              totalFee: totalFee,
              outTradeNo: outTradeNo
            }
          }).then(res => {
            let payParas = res.result;
            if (payParas.package == 'prepay_id=') {
              // a.统一下单 参数获取失败
              wx.hideLoading();
              wx.showModal({
                title: '发起支付失败',
                content: '请检查您的网络状态后再试',
                showCancel: false
              })
              return;
            } else {
              // b.统一下单 参数获取成功

              //************   客户端调起支付: wx.requestPayment  ************
              //(1)记录preypay_id，后续发送模板时需要用到
              that.data.prepayId = payParas.package.split('=')[1];
              //(2)发起支付请求
              wx.requestPayment({
                'timeStamp': payParas.timeStamp + '',
                'nonceStr': payParas.nonceStr,
                'package': payParas.package,
                'signType': 'MD5',
                'paySign': payParas.paySign,
                'complete': function (res) {
                  let errMsg = res.errMsg;

                  // a. 用户支付成功 并点击 [完成]
                  if (errMsg == 'requestPayment:ok') {
                    wx.hideLoading();
                    // canvas - loading显示
                    that.showWaitingToast()
                    /* 执行云函数[releaseOrder]:
                    1:将订单信息中转站信息 转正式订单信息(orderId)
                    2:删除临时订单信息(orderId)
                    3:通知打印(orderId)
                    */
                    util.releaseOrderByOrderId(that.data.orderId)
                      .then(res => {
                        if (res.result.result == 'success') {
                          // a.订单指令下达成功
                          // canvas - loading 隐藏
                          that.hideWaitingToast()

                          // 保存order信息至全局变量
                          console.log(res.result)
                          getApp().globalData.orderDetail = res.result.order;

                          //清空购物车信息
                          wx.removeStorageSync('cartList');

                          //跳转到订单详情页
                          wx.redirectTo({
                            url: '../../pages/orderDetail/orderDetail',
                          })
                        } else {
                          // b.订单指令下达失败
                          wx.showModal({
                            title: '店家网络繁忙中',
                            content: '请与店家沟通是否成功接单',
                            cancelText: '稍后确认',
                            confirmText: '立即确认',
                            complete: function (res) {
                              if (res.confirm) {
                                wx.makePhoneCall({
                                  phoneNumber: '17852859128',
                                })
                              }
                            }
                          })
                        }
                      })
                  }
                  // b. 用户取消支付
                  else if (errMsg == 'requestPayment:fail cancel') {
                    wx.showLoading({
                      title: '正在取消支付'
                    })
                    // 删除临时订单信息
                    util.deleteTempOrderByOrderId(that.data.orderId)
                      .then(res => {
                        wx.hideLoading()
                        wx.showToast({
                          title: '支付已取消',
                          icon: 'none'
                        })
                      })
                  }
                  // c. 其他情况
                  else {
                    console.log(JSON.stringify(res))
                    wx.hideLoading();
                    wx.showModal({
                      title: '支付失败',
                      content: '请检查网络，稍后再试',
                      showCancel: false
                    })
                  }
                }
              })
            }
          })
          .catch(err => {
            wx.showModal({
              title: '发起支付失败',
              content: '请检查网络状态，稍后再试',
              showCancel: false
            })
            wx.hideLoading();
          })
      }
    })
  },
  //---------------------------新版支付逻辑：使用云开发提供的微信支付sdk
  cloudWeiXinPay: function () {
    let that = this;
    wx.showLoading({
      title: '正在发起支付'
    });
    //************   获取需要传入的参函数   ************
    //(1)openid ：调用云函数自带openid
    //(2)订单总额:单位为分
    let totalFee = this.data.allPrice * 10 * 10 //订单总金额
    totalFee = Math.round(totalFee)
    console.log('totalFee:' + totalFee)
    //(3)订单号：生成唯一订单号，先生成，如果支付成功，则写入数据库成为正式订单号，否则废弃
    let outTradeNo = that.genOrderId();
    console.log("订单号：", outTradeNo)
    //----------------------------------------------------------------------------------

    //************   将订单信息上传至 订单信息中转站   ************
    that.uploadTempOrderInfo().then(res => {
      let result = res.result.result //订单信息是否上传成功
      if (result == 'fail')
      // a.临时信息上传失败
      {
        wx.hideLoading()
        wx.showModal({
          title: '发起支付失败',
          content: '请检查您的网络状态后再试',
          showCancel: false
        })
      } else {
        // b.临时信息上传成功
        //************   调用云支付:cloudWxPay   ************
        wx.cloud.callFunction({
          name: 'cloudWxPay',
          data: {
            totalFee: totalFee,
            outTradeNo: outTradeNo
          },
          success: res => {
            const payment = res.result.payment
            console.log('统一下单接口返回参数：', payment)
            wx.requestPayment({
              ...payment,
              complete(res) {
                let errMsg = res.errMsg;

                // a. 用户支付成功 并点击 [完成]
                if (errMsg == 'requestPayment:ok') {
                  // 重置计时器和订单信息
                  that.data.successOrderInfo = null
                  that.data.timer = null
                  // 隐藏正在支付 Loading
                  wx.hideLoading();
                  // 显示生成订单 Loading
                  that.showWaitingToast()
                  // ***************** 设置定时器，轮询查询订单生成
                  let time = 0
                  const db = wx.cloud.database();
                  that.data.timer = setInterval(() => {
                    time = time + 1000
                    console.log("查询订单生成计时器:" + time + "ms")
                    // 查询数据库
                    db.collection('orders').where({
                      orderId: that.data.orderId
                    }).get()
                    .then(res => {
                      console.log(res.data)
                      // 如果查询到订单信息
                      if (res.data[0]){
                        that.data.successOrderInfo = res.data[0];
                      }
                    }).then(res =>{
                      console.log('进入判断...')
                      if (that.data.successOrderInfo !== null) {
                        // 隐藏生成订单
                        that.hideWaitingToast()
                        // 保存order信息至全局变量
                        console.log(that.data.successOrderInfo)
                        getApp().globalData.orderDetail = that.data.successOrderInfo;
                        //清空购物车信息
                        wx.removeStorageSync('cartList');
                        //跳转到订单详情页
                        wx.redirectTo({
                          url: '../../pages/orderDetail/orderDetail',
                        })
                        //关闭计时器
                        clearInterval(that.data.timer)
                      } else if (time > 6000) {
                        that.show_famulei_loading(false)
                        clearInterval(that.data.timer)
                        wx.showModal({
                          title: '网络故障',
                          content: '请返回首页，进入我的订单查看订单详情！如有疑问，请联系店长',
                          showCancel: false,
                          confirmText: '我知道了',
                          complete: function (res) {
                            if (res.confirm) {
                              wx.navigateBack()
                            }
                          }
                        })
                      }
                    }).catch(err => {
                      console.log(err)
                      clearInterval(that.data.timer)
                    })
                  }, 1000, that.timer, time)
                }
                // b. 用户取消支付
                else if (errMsg == 'requestPayment:fail cancel') {
                  wx.showLoading({
                    title: '正在取消支付'
                  })
                  // 删除临时订单信息
                  util.deleteTempOrderByOrderId(that.data.orderId)
                    .then(res => {
                      wx.hideLoading()
                      wx.showToast({
                        title: '支付已取消',
                        icon: 'none'
                      })
                    })
                }
                // c. 其他情况
                else {
                  console.log(JSON.stringify(res))
                  wx.hideLoading();
                  wx.showModal({
                    title: '支付失败',
                    content: '请检查网络，稍后再试',
                    showCancel: false
                  })
                }
              }
            })
          },
          fail: err => {
            // a.统一下单 参数获取失败
            wx.hideLoading();
            wx.showModal({
              title: '发起支付失败',
              content: '请检查您的网络状态后再试',
              showCancel: false
            })
            console.error('cloudWxPay云函数调用失败', err)
          },
        })
      }
    })
  },
  //---------------------------进行支付动作后延时执行
  payStateConfirm: function () {
    let that = this
    console.log("wechatPay", that.data.weChatPay)
    let payRequest = payRequest
    let time = 0
    let timer = setInterval(() => {
      time = time + 1000
      console.log("计时器:" + time / 1000 + "s")
      console.log(that.data.weChatPay)
      // if (time > 10000){ //支付动作超过10s,并且

      // }

      //clearInterval(timer) //关闭计时器

    }, 1000, timer, time, that)
  },
  //---------------------------request：积分支付，获取用户会员信息状态并进行积分扣除
  payByVipPoints: function () {
    let that = this;
    //******获取需要传入的参函数******
    //(1)openid ：调用云函数自带openid
    //(2)订单总额:用户点击金额取整(直接舍弃小数部分)
    let totalFee = parseInt(this.data.allPrice) //订单总金额(元)
    //-----------校验:订单金额是否为0元
    console.log('totalFee:' + totalFee)
    if (totalFee == 0) {
      wx.showToast({
        title: '你在逗我吗？',
        icon: 'none'
      })
      return
    }
    //-----------积分支付二次确认
    wx.showModal({
      title: '积分支付',
      content: '点击确认支付将直接从您的会员卡账户扣除: ' + totalFee + ' 积分',
      confirmText: '确认支付',
      cancelText: '取消支付',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '支付中...'
          });
          //(3)订单号：生成唯一订单号，先生成，如果支付成功，则写入数据库成为正式订单号，否则废弃
          let outTradeNo = that.genOrderId();
          //----------------------------------------------------------------------------------
          let userInfo = wx.getStorageSync('userInfo')
          wx.cloud.callFunction({
              name: 'pointsPay',
              data: {
                openid: userInfo.openid,
                userid: userInfo.userid,
                totalFee: totalFee, //订单金额
                outTradeNo: outTradeNo, //订单号
                template_cardid: getApp().globalData.vipTemplateId //模板id
              }
            })
            .then(res => {
              let payResult = res.result
              console.log(payResult)
              if (res.result.result == 'fail') {
                wx.hideLoading()
                wx.showModal({
                  title: '积分支付失败',
                  content: res.result.error,
                  showCancel: false
                })
              } else if (res.result.result == 'success') {
                console.log('正在上传订单信息')
                wx.hideLoading();
                that.uploadOrderInfo(); //开始上传订单信息
              }
            })
            .catch(err => {
              wx.hideLoading()
              wx.showModal({
                title: '积分支付失败',
                content: '网络错误，请稍后再试',
                showCancel: false
              })
            })
        } else {
          console.log('用户取消积分支付')
        }
      }
    })


  },

  //---------------------------在前端生成唯一流水号
  genOrderId() {
    let orderId = ""; //订单号
    for (var i = 0; i < 8; i++) //8位随机数，用以加在时间戳后面。
    {
      orderId += Math.floor(Math.random() * 10);
    }
    orderId = 'FML' + new Date().getTime() + orderId; //时间戳，用来生成订单号。
    // 同步至内存
    this.data.orderId = orderId
    return orderId;
  },
  //---------------------------云函数[recordTempOrderInfo]执行：上传订单信息至中转站
  uploadTempOrderInfo: function () {
    let userInfo = wx.getStorageSync('userInfo')
    //获取订单数据
    var uploadData = {};
    uploadData.userId = userInfo.userid; //用户id
    uploadData.openId = userInfo.openid; //openid
    uploadData.orderTypeId = this.data.order.typeId; //订单类型
    uploadData.reserveTime = this.data.order.orderTime; //预约时间
    uploadData.address = this.data.order.addressInfo; //预约地址信息
    uploadData.totalCount = this.data.buyCount //订单总数量
    uploadData.totalCost = this.data.allPrice //订单总金额
    uploadData.deliveryCost = this.data.deliveryCost //订单配送费
    uploadData.extraDeliveryCost = this.data.extraDeliveryCost //订单附加服务费
    uploadData.orderRemark = this.data.orderRemark //订单备注
    uploadData.cartListData = this.data.cartListData //购物明细
    uploadData.payType = '待确认' //支付方式
    uploadData.orderId = this.data.orderId //临时订单ID
    uploadData.prepayId = this.data.prepayId //当前订单支付成功的prepayid,与支付者openid是对应关系
    //根据orderTypeId判断获取对应orderTypeName的值
    switch (uploadData.orderTypeId) {
      case 1:
        uploadData.orderTypeName = '在店即食'
        break;
      case 2:
        uploadData.orderTypeName = '预约到店'
        break;
      case 3:
        uploadData.orderTypeName = '外卖配送'
        break;
      default:
        uploadData.orderTypeName = '获取错误'
    }
    var that = this;
    return wx.cloud.callFunction({
      name: 'recordTempOrderInfo',
      data: {
        uploadData: JSON.stringify(uploadData)
      }
    })
  },
  //---------------------------云函数[recordTempOrderInfo]：上传订单信息至中转站

  //---------------------------发起request：上传订单信息至服务器，并生成订单编码
  uploadOrderInfo: function () {
    let userInfo = wx.getStorageSync('userInfo')
    //打开提示框：正在生成订单编号
    this.showWaitingToast();
    //获取必要数据
    var uploadData = {};
    uploadData.userId = userInfo.userid; //用户id
    uploadData.openId = userInfo.openid; //openid
    uploadData.orderTypeId = this.data.order.typeId; //订单类型
    uploadData.reserveTime = this.data.order.orderTime; //预约时间
    uploadData.address = this.data.order.addressInfo; //预约地址信息
    uploadData.totalCount = this.data.buyCount //订单总数量
    uploadData.totalCost = this.data.allPrice //订单总金额
    uploadData.deliveryCost = this.data.deliveryCost //订单配送费
    uploadData.extraDeliveryCost = this.data.extraDeliveryCost //订单附加服务费
    uploadData.orderRemark = this.data.orderRemark //订单备注
    uploadData.cartListData = this.data.cartListData //购物明细
    uploadData.payType = this.data.payType[this.data.payTypeIndex] //支付方式
    uploadData.orderId = this.data.orderId //临时订单ID
    uploadData.prepayId = this.data.prepayId //当前订单支付成功的prepayid,与支付者openid是对应关系
    //根据orderTypeId判断获取对应orderTypeName的值
    switch (uploadData.orderTypeId) {
      case 1:
        uploadData.orderTypeName = '在店即食'
        break;
      case 2:
        uploadData.orderTypeName = '预约到店'
        break;
      case 3:
        uploadData.orderTypeName = '外卖配送'
        break;
      default:
        uploadData.orderTypeName = '获取错误'
    }
    var that = this;

    wx.cloud.callFunction({
        name: 'recordOrderInfo',
        data: {
          uploadData: JSON.stringify(uploadData)
        }
      })
      .then(res => {
        let result = res.result.result //订单号记录是否成功
        if (result == 'fail') //(1)失败
        {
          that.hideWaitingToast(); //关闭订单生成
          wx.showModal({
            title: '注意',
            content: '订单生成失败！若已支付成功,请依据凭据取餐即可',
            showCancel: false
          })
        } else //(2)成功
        {
          //将整个uploadData存储至全局变量：
          console.log(res.result)
          getApp().globalData.orderDetail = res.result.order;

          // 订单信息上传完成后，去通知打印机打印
          //-----------------------------------
          wx.cloud.callFunction({
            name: 'printOrder',
            data: {
              orderId: uploadData.orderId
            }
          }).then(res => {
            //-----------------------------------
            //关闭订单生成
            that.hideWaitingToast();
            wx.redirectTo({
              url: '../../pages/orderDetail/orderDetail',
            })
            //清空购物车信息
            wx.removeStorageSync('cartList');
            let result = res.result.result
            if (result == 'fail') {
              // 如果打印请求下发失败
              wx.showModal({
                title: '店家接单网络繁忙',
                content: '您的订单已成功生成，请与店家确认是否接单成功！',
                cancelText: '稍后确认',
                confirmText: '立马确认',
                complete: function (res) {
                  if (res.confirm) {
                    wx.makePhoneCall({
                      phoneNumber: '17852859128',
                    })
                  }
                }
              })
            } else {
              // 说明打印小票成功，无需操作其他内容
            }
          })
        }
      })
      .catch(err => {
        that.hideWaitingToast(); //关闭订单生成
        wx.showModal({
          title: '注意',
          content: '订单生成失败！若已支付成功,请依据凭据取餐即可',
          showCancel: false
        })
      })
  },

  //------------------------------在js中封装一个画圆环的函数drawProgressbg，canvas 画圆
  drawProgressbg: function () {
    // 使用 wx.createContext 获取绘图上下文 context
    var ctx = wx.createCanvasContext('canvasProgressbg')
    ctx.setLineWidth(4); // 设置圆环的宽度
    ctx.setStrokeStyle('#20183b'); // 设置圆环的颜色
    ctx.setLineCap('round') // 设置圆环端点的形状
    ctx.beginPath(); //开始一个新的路径
    ctx.arc(110, 110, 100, 0, 2 * Math.PI, false); //设置一个原点(100,100)，半径为90的圆的路径到当前路径
    ctx.stroke();
    //对当前路径进行描边
    ctx.draw();
  },

  //------------------------------封装一个画圆环的函数drawCircle
  drawCircle: function (step) {
    var context = wx.createCanvasContext('canvasProgress');
    // 设置渐变
    var gradient = context.createLinearGradient(200, 100, 100, 200);

    gradient.addColorStop("0", "#2661DD");
    gradient.addColorStop("0.5", "#40ED94");
    gradient.addColorStop("1.0", "#5956CC");
    context.setLineWidth(10);
    context.setStrokeStyle(gradient);
    context.setLineCap('round')
    context.beginPath();
    // 参数step 为绘制的圆环周长，从0到2为一周 。 -Math.PI / 2 将起始角设在12点钟位置 ，结束角通过改变 step 的值确定
    context.arc(110, 110, 100, -Math.PI / 2, step * Math.PI - Math.PI / 2, false);
    context.stroke();
    context.draw()
  },
  countInterval: function (duration) {
    // 设置倒计时 定时器 每100毫秒执行一次，计数器count+1 ,耗时[duration]秒绘一圈
    this.countTimer = setInterval(() => {
      if (this.data.count <= duration) {
        /* 绘制彩色圆环进度条  注意此处 传参 step 取值范围是0到2，
        所以 计数器 最大值 60 对应 2 做处理，计数器count=60的时候step=2*/
        this.drawCircle(this.data.count / (duration / 2))
        this.data.count++;
      } else {
        this.data.count = 0;
      }
    }, 100)
  },
  //封装好的方法，直接显示或隐藏订单生成等待界面

  showWaitingToast: function () {
    this.setData({
      showWaiting: true
    })
    this.drawProgressbg(); //原始黑底框
    this.countInterval(60);
  },

  hideWaitingToast: function () {
    var context = wx.createCanvasContext('canvasProgress');
    clearInterval(this.countTimer);
    this.setData({
      showWaiting: false,
      count: 0
    })
  },

  //------------------------------当点击的商品拥有折叠价格明细时，展开
  openDetailPriceClick: function (e) {
    let options = e.currentTarget.dataset.options; //加料描述
    let folded = e.currentTarget.dataset.folded; //折叠属性
    let id = e.currentTarget.dataset.id; //当前产品数据id

    if (options == '') {
      //如果没有小料，直接退出
      return;
    }
    let cartListData = this.data.cartListData;

    //进行取反操作
    cartListData[id].folded = !folded; //每次点击取反操作
    this.setData({
      cartListData: cartListData
    })
  },
  //---------------------------发送模板消息
  sendMessageToBoss: function () {
    let orderDetail = getApp().globalData.orderDetail

    let orderDescrib = '';
    //根据orderDetail中的的cartListData获取订单详情

    for (let i = 0; i < orderDetail.cartListData.length; i++) {
      orderDescrib += '名称:' + orderDetail.cartListData[i].name + '  加料:' + (orderDetail.cartListData[i].options == '' ? '无' : orderDetail.cartListData[i].options) + '  数量:' + orderDetail.cartListData[i].count + '\n'
    }
    let sendData = {
      touser: getApp().globalData.managerOpenId, //接收人openid
      template_id: 'CDPn4I3cEYxnS8QVtxMhXWqb-CB6jpamjs4xojkYRXA', //模板消息id
      page: "pages/manageOrders/manageOrders",
      form_id: this.data.prepayId,
      data: {
        keyword1: {
          value: orderDetail.simpleId.toString('0000') //订单取餐号
        },
        keyword2: {
          value: orderDetail.orderId //订单号
        },
        keyword3: {
          value: orderDetail.orderTypeName //订单类型
        },
        keyword4: {
          value: '￥' + orderDetail.totalcost //订单总金额
        },
        keyword5: {
          value: orderDescrib //订单详情
        },
        keyword6: {
          value: orderDetail.orderRemark //订单备注
        },
      },
      emphasis_keyword: "keyword1.DATA"
    };
    console.log(sendData);
    sendData = JSON.stringify(sendData);
    util.sendTemplate(sendData);
  },
})